﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConcordWinManager
{
    public class Contract
    {        
        public int id_contract;

        public int id_rezident;

        public int id_consultant;

        public int id_oplata_type;

        public int id_template;

        public int id_address_postavka;

        public Consultant consultant;

        /// <summary>
        /// Контрагент - заказчик
        /// </summary>
        public Contragent contragent;
        
        /// <summary>
        /// Резидент - исполнитель
        /// </summary>
        public Rezident rezident;
        
        ///// <summary>
        ///// Адрес установки
        ///// </summary>
        //public Address Address_install;

        /// <summary>
        /// Номер договора
        /// </summary>
        public string ContractNumber; // дд.мм.гггг-N

        /// <summary>
        /// Дата заключения
        /// </summary>
        public string DateZakl;

        /// <summary>
        /// Сумма предварительная
        /// </summary>
        public decimal SummPre;

        /// <summary>
        /// Сумма итоговая
        /// </summary>
        public decimal SummItog;

        /// <summary>
        /// Процент скидки
        /// </summary>
        public int SkidkaPercent;

        /// <summary>
        /// Стоимость работ
        /// </summary>
        public decimal SummWork;

        /// <summary>
        /// Примечание
        /// </summary>
        public string Note;

        /// <summary>
        /// Аванс
        /// </summary>
        public decimal Advance;

       // public Oplata OplataType;

        /// <summary>
        /// Шаблон договора
        /// </summary>
        public Template template_contract;

        /// <summary>
        /// Шаблон квитанции об оплате
        /// </summary>
        public Template template_check;

        /// <summary>
        /// Шаблон квитанции формы ПД-№4
        /// </summary>
        public Template template_pd4;

        /// <summary>
        /// Адрес поставки
        /// </summary>
        public Address address_postavka;

        public Rassrochka rassrochka;

        public Contract()
        {
            rezident = new Rezident();
            contragent = new Contragent();
            consultant = new Consultant();
            template_contract = new Template();
            template_check = new Template();
            template_pd4 = new Template();
            address_postavka = new Address();

            //rassrochka = new Rassrochka();
        }

        public void Insert()
        {
            DataSet ds=new DataSet();

            DB.query_table("SELECT MAX(dbo.Contract.NumAtDay) AS MaxContractNumber, CAST(GETDATE() AS date) AS DateNow" +
                " FROM dbo.Contract " +
                " WHERE dbo.Contract.Date_zakl = CAST(GETDATE() AS date)",
                "dbo.Contract", ref ds);

            string maxContractNumber = ds.Tables[0].Rows[0]["MaxContractNumber"].ToString();
            
            DateTime dt = Convert.ToDateTime(ds.Tables[0].Rows[0]["DateNow"]);

            string[] tmp = maxContractNumber.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

            int maxContractNumberAtDay = 0;
            if (tmp.Length > 0)
            {
                if (int.TryParse(tmp[tmp.Length - 1], out maxContractNumberAtDay))
                {
                    ;
                }                
            }

           // maxContractNumberInDay++;

            this.ContractNumber = string.Format("{0}.{1}.{2}-{3}",
                dt.Day.ToString("0#"),
                dt.Month.ToString("0#"), dt.Year, ++maxContractNumberAtDay);

            this.DateZakl = string.Format("{0}-{1}-{2}", dt.Year, dt.Month, dt.Day);

            string query1 = string.Format("INSERT INTO dbo.Contract " +
                " (Contract_number, id_contragent, Date_zakl, id_rezident, id_template, " +
                " Summ_itog, Summ_pre, id_consultant, Skidka_percent, Summ_work, Note, id_oplata_type, NumAtDay, id_address_postavka) " +
                " VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}')",
                //string.Format("{0}.{1}.{2}-{3}", dt.Day.ToString("0#"), dt.Month.ToString("0#"), dt.Year, maxContractNumberAtDay),
                this.ContractNumber,
                this.contragent.id_contragent,
                this.DateZakl, //string.Format("{0}-{1}-{2}", dt.Year, dt.Month, dt.Day),
                this.rezident.id_rezident,
                this.template_contract.id_template,                
                this.SummItog.ToString().Replace(',', '.'),
                this.SummPre.ToString().Replace(',', '.'),
                this.consultant.id_consultant,
                this.SkidkaPercent.ToString().Replace(',', '.'),
                this.SummWork.ToString().Replace(',', '.'),
                this.Note,// != null ? this.Note : "",
                this.id_oplata_type,
                maxContractNumberAtDay,
                this.id_address_postavka
                );

            

            //Console.WriteLine(query1);
            DB.execute_sql(query1);

            this.id_contract = DB.max_num("dbo.Contract", "id_contract");


            //Внесение оплаты (аванс)

            Oplata oplata = new Oplata();

            oplata.contract = this;

            oplata.Definition = string.Format("оплата по договору {0} от {1}",
                this.ContractNumber,
                string.Format("{0}.{1}.{2}", dt.Day.ToString("0#"), dt.Month.ToString("0#"), dt.Year));

            oplata.DateOplata = dt;
            oplata.Summ = this.Advance;
            oplata.id_contract = this.id_contract;
            oplata.template_check = this.template_check; 
            
            oplata.Insert();

            //Добавление информации о рассрочке

            if (this.rassrochka != null)
            {
                this.rassrochka.Insert(this.id_contract);
            }
        }

        public Contract SelectById(int id)
        {
            DataSet ds = new DataSet();
            DB.query_table("SELECT * FROM dbo.Contract WHERE id_contract = " + id, "dbo.Contract", ref ds);

            this.id_contract = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_contract"].ToString());
            this.DateZakl = ds.Tables["dbo.Contract"].Rows[0]["Date_zakl"].ToString();
            this.ContractNumber = ds.Tables["dbo.Contract"].Rows[0]["Contract_Number"].ToString();
            this.Note = ds.Tables["dbo.Contract"].Rows[0]["Note"].ToString();
            this.id_rezident = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_rezident"].ToString());            
            this.contragent.id_contragent = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_contragent"].ToString());

            this.id_consultant = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_consultant"].ToString());
            this.SummItog = decimal.Parse(ds.Tables["dbo.Contract"].Rows[0]["Summ_itog"].ToString());
            this.SummPre = decimal.Parse(ds.Tables["dbo.Contract"].Rows[0]["Summ_pre"].ToString());
            this.SummWork = decimal.Parse(ds.Tables["dbo.Contract"].Rows[0]["Summ_work"].ToString());
            this.id_oplata_type = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_oplata_type"].ToString());
            this.id_template = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_template"].ToString());
            this.id_address_postavka = int.Parse(ds.Tables["dbo.Contract"].Rows[0]["id_address_postavka"].ToString());            

            this.contragent.SelectById(this.contragent.id_contragent);
            this.rezident.SelectById(this.id_rezident);
            this.consultant.SelectById(this.id_consultant);
            this.template_contract.SelectById(this.id_template);

            this.address_postavka.SelectById(this.id_address_postavka);

            if (this.id_oplata_type > 1)
            {
                this.rassrochka = new Rassrochka();
                this.rassrochka.SelectByIdContract(id);
            }

            return this;
        }

        public void SelectAll(ref DataSet ds)
        {
            //DB.query_table("SELECT * FROM dbo.View_Contract_FL ", "dbo.View_Contract_FL", ref ds);
            DB.query_table("EXEC dbo.GetAllContracts ", "dbo.Test", ref ds);
        }

        public void SelectByArgs()
        {
            ;
        }

        public void Update()
        {
            ;
        }

        /// <summary>
        /// Удаление договора
        /// </summary>
        /// <param name="id">ИД договора</param>
        /// <param name="id_consultant_who_delete">ИД консультанта, кто удалил</param>
        /// <param name="reasonDelete">Причина удаления</param>
        /// <param name="showInReport">Отображать в отчетах</param>
        /// <returns>Успешность удаления</returns>
        public bool DeleteById(int id, int id_consultant_who_delete, string reasonDelete, bool showInReport)
        {
            try
            {
                DataSet ds = new DataSet();
                string query1 = string.Format("UPDATE dbo.Contract SET id_consultant_who_delete = '{0}', ReasonDelete = '{1}', " +
                    " ShowInReport = '{2}', Deleted = 'True', DateDelete = CAST(GETDATE() AS date) " +
                    " WHERE id_contract = '{3}'",
                    id_consultant_who_delete,
                    reasonDelete,
                    showInReport,
                    id);

                DB.query_table(query1, "dbo.Contract", ref ds);
            }
            catch (Exception ex)
            {
                string s = ex.ToString();
                return false;
            }

            //удаление прошло успешно
            return true;
        }


        public Contract GetInfo(int id_contract, ref DataSet ds)
        {
            //this.SelectById(id_contract);


            DB.query_table(string.Format("EXEC dbo.GetContractInfo_0_2_15_0 '{0}'", id_contract), "dbo.GetContractInfo_0_2_13_0", ref ds);
            return this;
        }
    }
}
